<?php
namespace App\Think\SdkGame;

class YBCP{


    // 后台账号/密码：admin/aa123123
    // 商户密钥：2e268962384eb17f

    public function __construct()
    {

        // api地址
        $this->api_url  = 'https://api.baote.com/';
        $this->pull_url = 'https://pull.baote.com/';
        //游戏地址
        $this->mobile_url = 'https://h5.baote.com/';
        $this->pc_url = 'https://pc.baote.com/';

        $this->md5key   = '2e268962384eb17f';
        $this->merchant = 'btty';

        $this->plat_type  = 'YBCP';
        $this->password_init = md5('baote123A');
    }

    /**
     * 注册
     */
    public function register($param){
        $req_data = array(
            'member'     => $param['account'],
            'memberType' => 1,
            'password'   => $this->password_init,
            'merchant'   => $this->merchant,
            "doubleList" => '',
            'normalList' => '',
            'timestamp'  => $this->timestamp(),
        );
        $post_param = $this->build_params($req_data);
        $res = $this->sendRequest('boracay/api/member/create', $post_param, 1, 'json');
        return $res;
    }
    /**
     * 获取登录链接
     */
    public function login($param){
        $device = @$param['device'] == 'pc' ? 0 : 1;
        $req_data = array(
            'member'     => $param['account'],
            'password'   => $this->password_init,
            'merchant'   => $this->merchant,
            'timestamp'  => $this->timestamp(),
        );
        $post_param = $this->build_params($req_data);
        $res = $this->sendRequest('boracay/api/member/login', $post_param);
        //未注册，则先注册
        // if($res['code'] == -709){
        //     $res = $this->register($param);
        //     $post_param = $this->build_params($req_data);
        //     $res = $this->sendRequest('boracay/api/member/login', $post_param);
        // } 
        //返回数据处理
        $ret = [ 'code'=>$res['code'], 'token'=>@$res['data']['token'] ];
        if(!$device){
            $ret['url'] = $this->pc_url;
        }else{
            $ret['url'] = $this->mobile_url."?token={$ret['token']}";
        }
        return $ret;
    }
    /**
     * 获取余额
     */
    public function balance($param){
        $req_data = array(
            'member'     => $param['account'],
            'merchant'   => $this->merchant,
            'timestamp'  => $this->timestamp(),
        );
        $post_param = $this->build_params($req_data);
        $res = $this->sendRequest('boracay/api/nofreemember/balanceQuery', $post_param, 1, 'json');
        return ['code'=>$res['code'], 'balance'=>(float)$res['data']['amount'] ];
    }

    /**
     * 转入资金(上分)
     */
    public function transIn($param){
        $req_data = array(
            'member'          => $param['account'],
            'merchantAccount' => $this->merchant,
            'transferType'    => 1,
            'amount'          => $param['money'],
            'notifyId'        => $param['orderid'],

            'timestamp'       => $this->timestamp(),
        );
        $post_param = $this->build_params($req_data);
        $res = $this->sendRequest('boracay/api/nofreemember/transferBalance', $post_param, 1, 'json');
        return $res;
    }
    /**
     * 转出资金(下分)
     */
    public function transOut($param){
        $req_data = array(
            'member'          => $param['account'],
            'merchantAccount' => $this->merchant,
            'transferType'    => 2,
            'amount'          => $param['money'],
            'notifyId'        => $param['orderid'],

            'timestamp'       => $this->timestamp(),
        );
        $post_param = $this->build_params($req_data);
        $res = $this->sendRequest('boracay/api/nofreemember/transferBalance', $post_param, 1, 'json');
        return $res;
    }
    /**
     * 可转出资金查询(下分额度)
     */
    // public function transOutInfo($param){
    //     $req_data = array(
    //         "account" => $param['account']
    //     );
    //     $url = $this->build_params('transferOut');
    //     $res = $this->sendRequest($url, $req_data);
    //     return $res;
    // }


    /**
     * 游戏注单拉取
     */
    public function gameLogSync($param){

        $startTime = !empty($param['startTime']) ? strtotime($param['startTime']) : time();

        //数据返回处理
        $list = $this->down_json_data('_temp_json', $startTime);
        $rs = $raw_data = [];
        if(is_array($list) && count($list) > 0){
            foreach ($list as $k => $v) {
                //取消状态的订单不记录
                if($v['cancelStatus'] == true || empty($v['orderId'])) continue;

                $status = $this->status($v['betStatus'], $v['cancelStatus']);
                //流水
                if($v['profitAmount'] < 0)  $money_valid = -$v['profitAmount']<$v['betMoney'] ? -$v['profitAmount'] : $v['betMoney'];
                if($v['profitAmount'] >= 0) $money_valid = $v['profitAmount']<$v['betMoney'] ? $v['profitAmount'] : $v['betMoney'];
                //游戏记录处理
                $rs[$k] = [
                    'plat_type'     => $this->plat_type,
                    'game_type'     => $v['ticketId'],
                    'game_name'     => $v['ticketName'],
                    'game_user'     => $v['memberAccount'],
                    'bet_id'        => $v['orderId'],
                    'money_bet'     => $v['betMoney'],
                    'money_valid'   => $money_valid,
                    'money_winlose' => $v['profitAmount'],
                    'money_fee'     => 0,
                    'createtime'    => strtotime($v['betTime']),
                    'updatetime'    => strtotime($v['updateAt']),
                    'status'        => $status,
                ];
                //源数据处理
                $raw_data[$k] = $v;
                $raw_data[$k]['plat_type'] = $this->plat_type;
                $raw_data[$k]['bet_id']    = $v['orderId'];
                $raw_data[$k]['status']    = $status;
                $raw_data[$k]['updatetime'] = strtotime($v['updateAt']);
            }
        }
        $res['list'] = $rs;
        $res['raw_data']  = $raw_data;
        $res['code'] = 1;
        return $res;
    }


    /**
     * --------------
     * 内部方法
     * --------------
     */
    
    // json文件下载
    function down_json_data($temp_file = '_temp', $time){
        $temp_file = RUNTIME_PATH.$temp_file;
        //获取远程文件并下载为临时文件
        // $sss = 23;//date('H');
        list($Ym, $d, $H, $i) = [date('Ym', $time), date('d', $time), str_pad(date('H', $time)-1,2,0,STR_PAD_LEFT), date('i', $time)];
        // if($i>=5) return [];
        $file_name = $this->pull_url."{$Ym}/{$d}/real/order/{$H}.json";
        //文件是否存在
        if(!$this->webfile_exists($file_name)) return [];
        $hostfile = fopen($file_name, 'r');
        $fh = fopen($temp_file, 'w');
        while (!feof($hostfile)) {
            $output = fread($hostfile, 10240);
            fwrite($fh, $output);
        }
        fclose($hostfile);
        fclose($fh);
        
        //读取临时文件写入内存
        $arr = [];
        $fh = fopen($temp_file, 'r');
        while (! feof($fh)) {
            $line = fgets($fh);
            $arr[] = json_decode($line, true);
        }
        fclose($fh);
        unset($temp_file);
        return $arr;
    }
    // json文件是否存在
    function webfile_exists($url)
    {
        $array = get_headers($url,1);
        if(preg_match('/200/',$array[0])){
            return true;
        }else{
            return false;
        }
    }


    private function status($betStatus=0, $cancelStatus=false){
        if($cancelStatus == true) return 2;
        if($betStatus == 5 || $betStatus == 2 || $betStatus == 3) return 1;
        return 0;
    }

    private function sendRequest($url, $post_data=array(), $req_type=1, $contentType='form'){
        $url = $this->api_url.$url;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //POST
        if($req_type == 1){ 
            curl_setopt($ch, CURLOPT_POST, 1);
            if($contentType == 'json'){
                $jsonStr = json_encode($post_data);
                curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                        'Content-Type: application/json; charset=utf-8',
                        'Content-Length: ' . strlen($jsonStr)
                    )
                );
            }
            if($contentType == 'form'){
                $jsonStr = $post_data;
            }
            
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
        }
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $contents = curl_exec($ch);
        curl_close($ch);
        $contents = json_decode($contents, true);
        // echo $url."\n";
        // print_r($jsonStr);
        // print_r($contents);

        //业务处理
        $res = $contents;
        if(!isset($res['code'])){
          $res['code'] = -1;
          return $res;  
        } 
        if($res['code'] == 0){
            $res['code'] = 1;  
        }else{
            $res['code'] = -$res['code'];
        }
        return $res;
    }

    
    private function build_params($param){
        ksort($param);
        $sign = '';
        foreach ($param as $k => $v) $sign .= $k.$v;
        $sign = md5($sign.$this->md5key);
        $param['sign'] = $sign;
        return $param;
    }
    private function timestamp(){
        return (time()+8*3600)*1000;
    }

}

